package com.aceslideshows.common.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.HibernateException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.aceslideshows.common.dao.GenericDao;

/**
 * This class serves as a concrete class for the base dao methods that aren't tied to any specializations. Can be used
 * for standard CRUD operations.
 * </p>
 * 
 */
public class GenericDaoHibernateImpl<T, PK extends Serializable> extends HibernateDaoSupport implements
    GenericDao<T, PK>
{

    private Class<T> type;

    public GenericDaoHibernateImpl( Class<T> type )
    {
        this.type = type;
    }

    public void delete( T persistentObject )
    {
        getHibernateTemplate().delete( persistentObject );
    }

    @SuppressWarnings("unchecked")
    public T find( PK id )
    {
        return (T) getHibernateTemplate().get( type, id );
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll()
    {
        return getHibernateTemplate().find( "from " + type.getName() );
    }

    public Class<T> getType()
    {
        return type;
    }

    public void saveOrUpdate( T o )
    {
        getHibernateTemplate().saveOrUpdate( o );
    }

    public void refresh( T o )
    {
        getHibernateTemplate().refresh( o );
    }

    public void setType( Class<T> type )
    {
        this.type = type;
    }

    @SuppressWarnings("unchecked")
    public T getFirst( List list )
    {
        if ( list != null && list.size() > 1 )
        {
            throw new HibernateException( "More than one row was returned" );
        }

        return getFirstOfMany( list );
    }

    @SuppressWarnings("unchecked")
    public T getFirstOfMany( List list )
    {
        T ret = null;

        if ( list != null && list.isEmpty() == false )
        {
            ret = (T) list.get( 0 );
        }
        return ret;
    }
}
